package com.wy.user.service.impl;

import com.alibaba.nacos.common.util.Md5Utils;
import com.wy.common.utils.R;
import com.wy.user.util.JwtUtil;
import com.wy.user.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wy.common.utils.PageUtils;
import com.wy.common.utils.Query;

import com.wy.user.dao.UserDao;
import com.wy.user.entity.UserEntity;
import com.wy.user.service.UserService;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {
    @SuppressWarnings("all")
    @Autowired
    private UserDao userDao;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(params),
                new QueryWrapper<UserEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R loginAdd(UserEntity userEntity) {
        //注册时间
        userEntity.setRegisterData(new Date());
        //盐
        userEntity.setSalt(MD5Util.salt());
        //加盐加密后的密码
        userEntity.setPassword(MD5Util.md5Code(userEntity.getPassword(),2));
        userDao.insert(userEntity);
        return R.ok();
    }

    @Override
    public R login(UserEntity userEntity) {
        UserEntity user = userDao.login(userEntity.getId());
        if (user!=null) {
            String token = jwtUtil.createJWT(user.getId() + "", user.getNickname(), "token");
            String s = MD5Util.md5Code(userEntity.getPassword(), 2);
            if (user.getPassword().equals(s)) {
                user.setToken(token);
                user.setLastLoginData(new Date());
                user.setLoginCount(user.getLoginCount()+1);
                userDao.updateById(user);
                return R.ok().put("user",user);
            }
        }
        return R.error();
    }

}